package com.res.service.impl;

import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.res.entity.Subjects;
import com.res.repository.SubjectsRepository;
import com.res.service.SubjectsService;
@Service
public class SubjectsServiceImpl implements SubjectsService {
	
	@Autowired
	private SubjectsRepository subjectsRepository;

	@Override
	public Page<Subjects> findByMoHu(Subjects s, Pageable pageable) {
		// TODO Auto-generated method stub
		return subjectsRepository.findAll(get(s), pageable);
	}

	private Specification<Subjects> get(Subjects s) {
		// TODO Auto-generated method stub
		return new Specification<Subjects>() {

			@Override
			public Predicate toPredicate(Root<Subjects> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
				// TODO Auto-generated method stub
				Predicate predicate = criteriaBuilder.conjunction();
				List<Expression<Boolean>> expressions = predicate.getExpressions();
				if(!StringUtils.isEmpty(s.getSname())) {
				expressions.add(criteriaBuilder.like(root.get("sname"), "%"+s.getSname()+"%"));
				}
				return predicate;
			}
		};
	}

	@Override
	public Subjects AddAndUpdateBySub(Subjects s) {
		// TODO Auto-generated method stub
		return subjectsRepository.saveAndFlush(s);
	}

	@Override
	public void deleteSub(Integer sid) {
		// TODO Auto-generated method stub
		subjectsRepository.deleteById(sid);
		
	}

}
